package com.yuanduan.mplus.view;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IntegerRes;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePopupWindow;
import com.cj.framework.app.BaseActivity;
import com.cj.framework.util.HttpImp;
import com.cj.framework.util.IHttp;
import com.cj.framework.util.RSAUtils;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;
import com.yuanduan.mplus.model.DBManager;
import com.yuanduan.mplus.model.entity.DriveRecordEntity;
import com.yuanduan.mplus.presenter.DriveRecordAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by cj on 2016/6/6.
 * Email:781806481@qq.com
 */
public class DriveRecordActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private Button btn_search;
    private Toolbar toolbar;
    private TextView tv_date1;
    private TextView tv_date2;
    private TimePopupWindow timePopupWindow1;
    private TimePopupWindow timePopupWindow2;
    private ListView listView;
    private DriveRecordAdapter adapter;
    private ProgressDialog progressDialog;

    private List<DriveRecordEntity> lists=new ArrayList<DriveRecordEntity>();
    private Date date2=new Date();
    private Date date1=new Date();
    private String phone=null;
    private IHttp iHttp=new HttpImp();
    private IHttp.HttpInfoCallbackWithIndex callback=new IHttp.HttpInfoCallbackWithIndex() {
        @Override
        public void onSucceed(Object result, int index) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    progressDialog.dismiss();
                }
            },1000);
            lists.clear();
            ArrayList<Integer> recordID=new ArrayList<>();
            ArrayList<String> carNumber=new ArrayList<>();
            ArrayList<String> startTime=new ArrayList<>();
            ArrayList<String> endTime=new ArrayList<>();
            ArrayList<String> distance=new ArrayList<>();
            //填入数据
            String data= RSAUtils.decryptWithRSA((String) result);
            try {
                JSONObject jsonObject=new JSONObject(data);
                if(jsonObject.getInt("RS")!=1){
                    return;
                }else{
                    JSONArray record=jsonObject.getJSONArray("Record");
                    for(int i=0;i<record.length();i++){
                        JSONObject object=record.getJSONObject(i);
                        recordID.add(object.getInt("RecordID"));
                        carNumber.add(object.getString("CarNumber"));
                        startTime.add(object.getString("StartTimer"));
                        endTime.add(object.getString("EndTimer"));
                        distance.add(object.getString("Mileage"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if(Config.userType==1||Config.userType==2){
                for(int i=0;i<recordID.size();i++){
                    DriveRecordEntity entity=new DriveRecordEntity();
                    entity.setRecordID(recordID.get(i));
                    entity.setCarNumber(carNumber.get(i));
                    entity.setStartTime(startTime.get(i));
                    entity.setEndTime(endTime.get(i));
                    entity.setDistance(distance.get(i));
                    lists.add(entity);
                }
            }else{
                DriveRecordEntity entity=new DriveRecordEntity(1,"浙G1100"+(int)(Math.random()*10),"2016-5-12 10:20:50","2016-5-12 10:21:50","10");
                DriveRecordEntity entity2=new DriveRecordEntity(2,"浙G1100"+(int)(Math.random()*10),"2016-5-13 10:20:50","2016-5-13 10:21:50","9");
                DriveRecordEntity entity3=new DriveRecordEntity(3,"浙G1100"+(int)(Math.random()*10),"2016-5-14 10:20:50","2016-5-14 10:21:50","90");
                lists.add(entity);
                lists.add(entity2);
                lists.add(entity3);
            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onFailed(Object result, int index) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    progressDialog.dismiss();
                }
            },1000);
            if(Config.userType==-1){
                DriveRecordEntity entity=new DriveRecordEntity(1,"浙G1100"+(int)(Math.random()*10),"2016-5-12 10:20:50","2016-5-12 10:21:50","10");
                DriveRecordEntity entity2=new DriveRecordEntity(2,"浙G1100"+(int)(Math.random()*10),"2016-5-13 10:20:50","2016-5-13 10:21:50","9");
                DriveRecordEntity entity3=new DriveRecordEntity(3,"浙G1100"+(int)(Math.random()*10),"2016-5-14 10:20:50","2016-5-14 10:21:50","90");
                lists.add(entity);
                lists.add(entity2);
                lists.add(entity3);
                adapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected void findId() {
        listView= (ListView) findViewById(R.id.driverecord_listview);
        btn_search= (Button) findViewById(R.id.driverecord_btn_search);
        toolbar= (Toolbar) findViewById(R.id.toolbar);
        tv_date1= (TextView) findViewById(R.id.driverecord_tv_date1);
        tv_date2= (TextView) findViewById(R.id.driverecord_tv_date2);
    }

    @Override
    protected void logic() {
        if(Config.userType==1){
            phone= DBManager.getInstance(getApplicationContext()).getUser().getUserPhone();
        }else if(Config.userType==2){

        }else{
            //游客
        }
        progressDialog=new ProgressDialog(this);
        adapter=new DriveRecordAdapter(this,lists);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        timePopupWindow1 =new TimePopupWindow(this, TimePopupWindow.Type.YEAR_MONTH_DAY);
        timePopupWindow2=new TimePopupWindow(this, TimePopupWindow.Type.YEAR_MONTH_DAY);
        if(Config.userType==1){
            toolbar.setTitle("行车记录");
        }else if(Config.userType==2){
            toolbar.setTitle("王小丫的行车记录");
        }else{
            toolbar.setTitle("行车记录");
        }
        toolbar.setNavigationIcon(R.mipmap.back_arrow_black);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DriveRecordActivity.this.finish();
            }
        });
        timePopupWindow1.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                date1=date;
                tv_date1.setText(formatDate(date));
            }
        });
        timePopupWindow2.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                date2=date;
                tv_date2.setText(formatDate(date));
            }
        });
        tv_date1.setClickable(true);
        tv_date2.setClickable(true);
        tv_date1.setOnClickListener(this);
        tv_date2.setOnClickListener(this);
        btn_search.setOnClickListener(this);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_driverecord;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.driverecord_tv_date1:
                timePopupWindow1.showAtLocation(tv_date1, Gravity.CENTER,0,0,new Date());
                break;
            case R.id.driverecord_tv_date2:
                timePopupWindow2.showAtLocation(tv_date2, Gravity.CENTER,0,0,new Date());
                break;
            case R.id.driverecord_btn_search:
                HashMap<String,String> hashMap=new HashMap<>();
                hashMap.put("UserPhone",phone);
                hashMap.put("StartTimer",date1.getTime()/1000+"");
                hashMap.put("EndTimer",date2.getTime()/1000+"");
                hashMap.put("sorting","-1");
                iHttp.httpInfoPostWithIndex(Config.URL+Config.RECORDSEARCH,Config.translateMap(hashMap),callback,0);
                progressDialog.show();
                break;
        }
    }

    private String formatDate(Date date){
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    private Handler handler=new Handler();

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //打开行车记录详情页
        Bundle bundle=new Bundle();
        bundle.putInt("RecordID",lists.get(position).getRecordID());
        openActivity(DriveRecordDetailActivity.class,bundle);
    }
}
